<template>
  <teleport to="body">
    <div 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300"
      :class="{ 'opacity-0 pointer-events-none': !visible }"
      @click="handleClose"
    >
      <div 
        class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300"
        :class="{ 'scale-95 opacity-0': !visible, 'scale-100 opacity-100': visible }"
        @click.stop
      >
        <!-- 模态框头部 -->
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-medium text-gray-900">{{ title }}</h3>
          <button 
            class="text-gray-400 hover:text-gray-500 focus:outline-none"
            @click="handleClose"
            aria-label="关闭"
          >
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <!-- 模态框内容 -->
        <div class="px-6 py-5">
          <form @submit.prevent="handleSubmit">
            <div class="space-y-4">
              <div>
                <label for="permission-name" class="block text-sm font-medium text-gray-700 mb-1">
                  权限名称 <span class="text-red-500">*</span>
                </label>
                <input
                  id="permission-name"
                  v-model="form.name"
                  type="text"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                  placeholder="输入权限名称"
                  :class="errors.name ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''"
                  @blur="validateField('name')"
                >
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>
              
              <div>
                <label for="permission-code" class="block text-sm font-medium text-gray-700 mb-1">
                  权限编码 <span class="text-red-500">*</span>
                </label>
                <input
                  id="permission-code"
                  v-model="form.code"
                  type="text"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors font-mono text-sm"
                  placeholder="例如: system:user:create"
                  :class="errors.code ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''"
                  @blur="validateField('code')"
                >
                <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
                <p class="mt-1 text-xs text-gray-500" v-else>
                  建议使用"资源:操作"格式，如"user:edit"
                </p>
              </div>
              
              <div>
                <label for="permission-group" class="block text-sm font-medium text-gray-700 mb-1">
                  权限组 <span class="text-red-500">*</span>
                </label>
                <select
                  id="permission-group"
                  v-model="form.groupId"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                  :class="errors.groupId ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''"
                  @change="validateField('groupId')"
                >
                  <option value="">请选择权限组</option>
                  <option v-for="group in permissionGroups" :key="group.id" :value="group.id">
                    {{ group.name }}
                  </option>
                </select>
                <p v-if="errors.groupId" class="mt-1 text-sm text-red-600">{{ errors.groupId }}</p>
              </div>
              
              <div>
                <label for="permission-description" class="block text-sm font-medium text-gray-700 mb-1">
                  描述
                </label>
                <textarea
                  id="permission-description"
                  v-model="form.description"
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                  placeholder="描述该权限的用途和范围"
                ></textarea>
              </div>
              
              <div v-if="form.isSystemPermission" class="bg-yellow-50 p-3 rounded-md flex items-start">
                <i class="fa fa-info-circle text-yellow-500 mt-0.5 mr-2"></i>
                <p class="text-sm text-yellow-700">
                  这是系统内置权限，部分属性不可修改
                </p>
              </div>
            </div>
          </form>
        </div>
        
        <!-- 模态框底部 -->
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button
            type="button"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
            @click="handleClose"
          >
            取消
          </button>
          <button
            type="button"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
            @click="handleSubmit"
            :disabled="submitting"
          >
            <i class="fa fa-save mr-1"></i>
            <span v-if="!submitting">保存</span>
            <span v-if="submitting" class="flex items-center">
              <i class="fa fa-spinner fa-spin mr-1"></i> 保存中...
            </span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script>
import { ref, watch, computed } from 'vue';

export default {
  name: 'PermissionModal',
  props: {
    // 控制模态框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 权限数据，编辑时传入
    permission: {
      type: Object,
      default: () => ({})
    },
    // 权限组列表
    permissionGroups: {
      type: Array,
      default: () => []
    },
    // 模态框标题
    title: {
      type: String,
      default: '权限设置'
    }
  },
  emits: ['close', 'save'],
  setup(props, { emit }) {
    // 表单数据
    const form = ref({
      id: '',
      name: '',
      code: '',
      groupId: '',
      description: '',
      isSystemPermission: false
    });
    
    // 错误信息
    const errors = ref({
      name: '',
      code: '',
      groupId: ''
    });
    
    // 提交状态
    const submitting = ref(false);
    
    // 监听权限数据变化，初始化表单
    watch(() => props.permission, (newVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        form.value = { ...newVal };
      } else {
        form.value = {
          id: '',
          name: '',
          code: '',
          groupId: '',
          description: '',
          isSystemPermission: false
        };
      }
      // 重置错误信息
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = '';
      });
    }, { immediate: true });
    
    // 验证单个字段
    const validateField = (field) => {
      const value = form.value[field];
      errors.value[field] = '';
      
      switch (field) {
        case 'name':
          if (!value || value.trim() === '') {
            errors.value[field] = '请输入权限名称';
          } else if (value.length > 50) {
            errors.value[field] = '权限名称不能超过50个字符';
          }
          break;
          
        case 'code':
          if (!value || value.trim() === '') {
            errors.value[field] = '请输入权限编码';
          } else if (!/^[a-zA-Z0-9:_]+$/.test(value)) {
            errors.value[field] = '权限编码只能包含字母、数字、冒号和下划线';
          } else if (value.length > 100) {
            errors.value[field] = '权限编码不能超过100个字符';
          }
          break;
          
        case 'groupId':
          if (!value) {
            errors.value[field] = '请选择权限组';
          }
          break;
      }
    };
    
    // 完整表单验证
    const validateForm = () => {
      let isValid = true;
      
      // 验证所有必要字段
      ['name', 'code', 'groupId'].forEach(field => {
        validateField(field);
        if (errors.value[field]) {
          isValid = false;
        }
      });
      
      return isValid;
    };
    
    // 处理提交
    const handleSubmit = async () => {
      if (submitting.value) return;
      
      if (!validateForm()) {
        // 自动滚动到第一个错误字段
        const firstErrorField = Object.keys(errors.value).find(key => errors.value[key]);
        if (firstErrorField) {
          document.getElementById(`permission-${firstErrorField}`).focus();
        }
        return;
      }
      
      try {
        submitting.value = true;
        // 触发保存事件，将表单数据传递给父组件
        emit('save', { ...form.value });
      } catch (error) {
        console.error('提交权限数据失败:', error);
      } finally {
        submitting.value = false;
      }
    };
    
    // 处理关闭
    const handleClose = () => {
      if (!submitting.value) {
        emit('close');
      }
    };
    
    return {
      form,
      errors,
      submitting,
      validateField,
      handleSubmit,
      handleClose
    };
  }
};
</script>
